<template>
  <div v-if="hasError" class="error-boundary">
    <div class="error-content">
      <div class="error-icon">⚠️</div>
      <h2 class="error-title">{{ $t('error.title', { default: '出现错误' }) }}</h2>
      <p class="error-message">{{ errorMessage }}</p>
      <div class="error-actions">
        <button @click="reload" class="btn-primary">
          {{ $t('error.reload', { default: '重新加载' }) }}
        </button>
        <button @click="goHome" class="btn-secondary">
          {{ $t('error.goHome', { default: '返回首页' }) }}
        </button>
      </div>
      <details v-if="errorStack" class="error-details">
        <summary>{{ $t('error.details', { default: '错误详情' }) }}</summary>
        <pre>{{ errorStack }}</pre>
      </details>
    </div>
  </div>
  <slot v-else />
</template>

<script setup lang="ts">
import { ref, onErrorCaptured } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const hasError = ref(false)
const errorMessage = ref('')
const errorStack = ref('')

onErrorCaptured((error: any) => {
  hasError.value = true
  errorMessage.value = error.message || '未知错误'
  errorStack.value = error.stack || ''

  // 记录错误到控制台
  console.error('ErrorBoundary caught error:', error)

  // 可以发送错误到监控服务
  // sendErrorToMonitor(error)

  return false // 阻止错误继续传播
})

const reload = () => {
  hasError.value = false
  window.location.reload()
}

const goHome = () => {
  hasError.value = false
  router.push('/')
}
</script>

<style scoped>
.error-boundary {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-secondary);
  padding: 20px;
}

.error-content {
  max-width: 600px;
  background: var(--card-bg);
  border-radius: 12px;
  padding: 40px;
  box-shadow: var(--card-shadow);
  text-align: center;
}

.error-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.error-title {
  font-size: 24px;
  color: var(--error-color);
  margin-bottom: 12px;
}

.error-message {
  font-size: 16px;
  color: var(--text-secondary);
  margin-bottom: 24px;
}

.error-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-bottom: 24px;
}

.btn-primary,
.btn-secondary {
  padding: 10px 24px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-primary {
  background: var(--primary-color);
  color: white;
}

.btn-primary:hover {
  background: var(--primary-hover);
}

.btn-secondary {
  background: var(--bg-tertiary);
  color: var(--text-primary);
}

.btn-secondary:hover {
  background: var(--bg-secondary);
}

.error-details {
  text-align: left;
  margin-top: 20px;
  padding: 16px;
  background: var(--bg-tertiary);
  border-radius: 6px;
}

.error-details summary {
  cursor: pointer;
  color: var(--text-secondary);
  font-size: 14px;
  margin-bottom: 12px;
}

.error-details pre {
  font-size: 12px;
  color: var(--text-primary);
  overflow-x: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>
